package com.ming.security.service.impl;

import com.ming.security.entity.Admin;
import com.ming.security.proxy.ArrayListProxy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class UserDetailServiceImpl implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 模拟数据库,查询用户信息
        Admin admin = getAdmin(username);
        //获取用户名、密码数据
        String password = admin.getPassword();
        //创建权限列表
        List<GrantedAuthority> authorities=new ArrayList<>();
        // 模拟数据库查询用户的角色列表
        List<String> roleList = getRole(username);
        roleList.forEach(role -> {
            authorities.add(new SimpleGrantedAuthority("ROLE_"+role));
        });
        // 查询用户的权限信息
        List<String> authList = getAuth(username);
        authList.forEach(auth -> {
            authorities.add(new SimpleGrantedAuthority(auth));
        });
        //创建用户对象
        return new User(username,password,authorities);

    }

    public Admin getAdmin(String username){
        Map<String,Admin> adminMap = new HashMap<>();
        adminMap.put("ming",new Admin().setPassword("95C90AA47733B9023C318D9914606339"));
        adminMap.put("admin",new Admin().setPassword("21232F297A57A5A743894A0E4A801FC3"));
        log.info("查询用户{}密码:{}",username,adminMap.get(username));
        return adminMap.get(username);
    }
    public List<String> getAuth(String username){
        Map<String,List<String>> authMap = new HashMap<>();
        authMap.put("admin",new ArrayListProxy<String>().addObject("SAVE").addObject("EDIT"));
        authMap.put("ming",new ArrayListProxy<String>().addObject("EDIT"));
        log.info("查询用户{}权限:{}",username,authMap.get(username));
        return authMap.get(username);
    }

    public List<String> getRole(String username){
        Map<String,List<String>> roleMap = new HashMap<>();
        roleMap.put("admin",new ArrayListProxy<String>().addObject("ADMIN").addObject("USER"));
        roleMap.put("ming",new ArrayListProxy<String>().addObject("USER"));
        log.info("查询用户{}角色:{}",username,roleMap.get(username));
        return roleMap.get(username);
    }

}
